package chapter17.Exercise;

/**
 * @Auther: Tx
 * @Date: 2022/6/19 19:20
 */
//模拟三个线程售票100张
public class Sellticket {
    public static void main(String[] args) {
        SellTicker01 sellTicker01 = new SellTicker01();
        SellTicker01 sellTicker02 = new SellTicker01();
        SellTicker01 sellTicker03 = new SellTicker01();
//      这里会出现超卖，因为线程执行的速度过快
      //  sellTicker01.start();
       // sellTicker02.start();
       // sellTicker03.start();
        System.out.println("使用接口方式");
        SellTicket02 sellTicket001 = new SellTicket02();
        new Thread(sellTicket001).start();//窗口一
        new Thread(sellTicket001).start();//窗口二
        new Thread(sellTicket001).start();//窗口三

    }
}

//继承Thread
class SellTicker01 extends Thread {
    private static int ticketCount = 100;

    @Override
    public void run() {
        while (true) {
            if (ticketCount <= 0) {
                System.out.println("ticket is all sold");
                break;
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("当前售票窗口是" + Thread.currentThread().getName() + "售出一张票" + "余额为" + (--ticketCount));
        }
    }
}

class SellTicket02 implements Runnable {
    private int ticketNum = 100;

    //让多个线程共享 ticketNum
    @Override
    public void run() {
        while (true) {
            if (ticketNum <= 0) {
                System.out.println("售票结束...");
                break;
            }//休眠 50 毫秒, 模拟
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口 " + Thread.currentThread().getName() + " 售出一张票" + " 剩余票数=" + (--ticketNum));
        }
    }
}